package com.example.service;

import com.example.entity.Comment;
import com.example.mongodb.CommentMongo;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
public class CommentService implements CommentMongo {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean insertComment(List<Comment> comment) {
        Collection<Comment> res = mongoTemplate.insert(comment, Comment.class);
        if (Objects.isNull(res)) {
            return false;
        } else {
            return true;
        }
    }

    public Boolean comments(Integer currentpage, Integer size) {
        PageRequest id = PageRequest.of(currentpage, size, Sort.by(Sort.Order.by("id")));
        Query query = new Query().with(id);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        if (Objects.isNull(comments)) {
            return false;
        } else {
            for (Comment comment : comments) {
                System.out.println(comment);
            }
            return true;
        }
    }

    public Boolean updateLikes(Long id) {
        Query id1 = new Query(Criteria.where("id").is(id));
        Update update = new Update();
        update.inc("likeNum",1);
        UpdateResult updateResult = mongoTemplate.updateFirst(id1, update, Comment.class);
        long modifiedCount = updateResult.getModifiedCount();
        if (modifiedCount > 0) {
            return true;
        } else {
            return false;
        }
    }
}
